<template>
  <div>
    <!-- title -->
    <PageTitle>
      {{ $t('menu.M_126868') }}
    </PageTitle>
    <el-card
      shadow="never"
      :body-style="{ padding: '0px' }"
      :page-size="pageSize"
      :total="totalRows"
      :current-page="pageIndex"
      @current-change="currentChangeHandle"
    >
      <el-form class="p-4" inline @submit.prevent.native>
        <el-form-item>
          <el-input
            maxlength="256"
            :placeholder="$t('merchant.name')"
            v-model="merchantName"
            @blur="() => (merchantName = merchantName.trim())"
            @keyup.enter.native="search((pageNo = 1))"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="w-8" @click="search((pageIndex = 1))">
            <svg-icon icon-class="search" />
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            v-permission="{
              permission: '126868.MANAGE'
            }"
            type="primary"
            class="w-8"
            @click="handleAdd()"
          >
            <svg-icon icon-class="plus" />
          </el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="listLoading" :show-overflow-tooltip="true" :data="tableData" stripe>
        <el-table-column :label="$t('merchant.merchant')" prop="name">
          <template v-slot="scope">
            <div
              :class="[verifyPermissionSet('126868') ? 'cursor-pointer' : '']"
              @click="
                verifyPermissionSet('126868')
                  ? handleClick({ command: 'details', row: scope.row })
                  : null
              "
            >
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('merchant.mid')" prop="mid" align="center" />
        <el-table-column
          prop="countryCode"
          align="center"
          min-width="120"
          :label="$t('user.country_or_region')"
          ><template v-slot="scope">
            {{ $t('country_or_region.' + scope.row.countryCode) }}
          </template></el-table-column
        >

        <el-table-column :label="$t('common.status')" prop="status" width="100">
          <template v-slot="{ row }">
            <el-tag
              :type="row.status == 0 ? 'danger' : row.status == 1 ? 'success' : ''"
              size="small"
            >
              <span>{{ statusFilter(row.status) }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.create_time')" prop="creTime" width="200">
          <template v-slot="{ row }">
            <div :title="timeFilter(row.creTime)">
              {{ dateFilter(row.creTime) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column width="75">
          <template v-slot="scope">
            <el-dropdown @command="handleClick">
              <el-button text class="w-8">
                <svg-icon icon-class="MoreFilled" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="beforeHandleCommand('setTopic', scope.row)">
                    <svg-icon icon-class="outlined-highlight" />
                    {{ $t('flypass.set_pass_enable') }}
                  </el-dropdown-item>
                  <el-dropdown-item :command="beforeHandleCommand('details', scope.row)">
                    <svg-icon icon-class="outlined-eye" />
                    {{ $t('merchant.merchantDetail') }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.status === 1 && verifyPermission('126868.MANAGE')"
                    :command="beforeHandleCommand('lock', scope.row)"
                  >
                    <svg-icon icon-class="Lock" />
                    {{ $t('user.lock') }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.status === 0 && verifyPermission('126868.MANAGE')"
                    :command="beforeHandleCommand('unlock', scope.row)"
                  >
                    <svg-icon icon-class="Unlock" />
                    {{ $t('user.unlock') }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="verifyPermission('126868.DELETE')"
                    :command="beforeHandleCommand('delete', scope.row)"
                  >
                    <svg-icon icon-class="Delete" />
                    {{ $t('common.delete') }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <add-merchant v-model="addMerchantVisible" @refresh="refresh" />
    <set-topic-dialog v-model:visible="setTopicVisible" @save="onSave" :mrch-id="mrchId" :pass-id="passId"/>
  </div>
</template>

<script>
import { deleteMerchant, getMerchantPage, lockMerchant, unlockMerchant } from '@/api/merchant'
import { timeFilter, dateFilter } from '@/filters'
import { verifyBtnPermission } from '@/utils'
import PageTitle from '@/components/PageTitle/index.vue'
import { hasPermissionSet } from '@/utils/auth'
import AddMerchant from './components/add-merchant.vue'
import SetTopicDialog from './components/set-topic-dialog.vue'

export default {
  components: {
    PageTitle,
    AddMerchant,
    SetTopicDialog
  },
  data() {
    return {
      loginUserName: '',
      tableData: [],
      listLoading: false,
      selectedData: [],
      paginationShow: true,
      merchantName: '',
      pageIndex: 1,
      pageSize: 10,
      totalRows: 0,
      operationType: '',
      addMerchantVisible: false,
      setTopicVisible: false,
      mrchId: null,
      passId: ''
    }
  },
  mounted() {
    const userInfo = JSON.parse(localStorage.getItem(this.$store.getters.keys.storage.username))
    this.loginUserName = userInfo.username
    this.search()
  },
  methods: {
    statusFilter(status) {
      const statusMap = {
        0: 'Locked',
        1: 'Valid'
      }
      return statusMap[status]
    },
    timeFilter,
    dateFilter,
    verifyPermissionSet(val) {
      return hasPermissionSet(val)
    },
    verifyPermission(val) {
      return verifyBtnPermission(val)
    },
    search() {
      this.listLoading = true
      getMerchantPage({
        pageNo: this.pageIndex,
        pageSize: this.pageSize,
        merchantName: this.merchantName
      })
        .then((res) => {
          this.listLoading = false
          this.tableData = res.data
          this.totalRows = res.rows
        })
        .catch((e) => {
          this.listLoading = false
          this.$confirmError(e)
        })
    },

    getLogo(logo) {
      if (logo) {
        const avatars = this.$store.getters.avatars.find((v) => v.name == logo)
        if (avatars) {
          return avatars.src
        }
      }
      return this.$store.getters.avatars[0].src
    },
    handleLock(row) {
      this.$confirm(this.$t('merchant.lock_merchant', { name: row.name }), this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        lockMerchant(row.mrchId)
          .then((res) => {
            this.$message({
              message: this.$t('user.lock_success'),
              type: 'success'
            })
            this.search()
          })
          .catch(this.$confirmError)
      })
    },
    handleUnlock(row) {
      this.$confirm(
        this.$t('merchant.unlock_merchant', { name: row.name }),
        this.$t('common.tips'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(() => {
        unlockMerchant(row.mrchId)
          .then((res) => {
            this.$message({
              message: this.$t('user.unlock_success'),
              type: 'success'
            })
            this.search()
          })
          .catch(this.$confirmError)
      })
    },
    onSave() {
      this.search()
    },
    handleDelete(row) {
      this.$confirm(this.$t('merchant.merchant_delete_confirm_tip', { mrchName: row.name }), '', {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        deleteMerchant(row.mrchId)
          .then((res) => {
            this.$message.success(this.$t('common.operate_success'))
            this.search()
          })
          .catch((e) => {
            this.$confirmError(e)
          })
      })
    },
    handleClick(val) {
      const command = val.command
      const row = val.row
      if (command === 'details') {
        this.$router.push({
          path: `/merchant/merchant-detail/` + row.mrchId
        })
      } else if (command === 'lock') {
        this.handleLock(row)
      } else if (command === 'unlock') {
        this.handleUnlock(row)
      } else if (command === 'delete') {
        this.handleDelete(row)
      } else if (command === 'setTopic') {
        this.setTopicVisible = true
        this.passId = row.passId
        this.mrchId = row.mrchId
      }
    },
    beforeHandleCommand(command, row) {
      return {
        row: row,
        command: command
      }
    },

    handleAdd() {
      this.addMerchantVisible = true
    },
    refresh() {
      ;(this.pageIndex = 1), (this.merchantName = ''), this.search()
    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.search()
    },
    currentChangeHandle(val) {
      this.pageIndex = val
      this.search()
    }
  }
}
</script>

<style lang="scss" scoped></style>
